package middleware

import (
	"context"
	"encoding/json"
	"net/http"
	"portal/internal/common"
	"portal/internal/config"
	"portal/internal/types"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
)

type AuthMiddleware struct {
	config config.Config
}

func NewAuthMiddleware(config config.Config) *AuthMiddleware {
	return &AuthMiddleware{
		config: config,
	}
}

func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("Authorization")
		if len(token) >0{
			rds, err := redis.NewRedis(redis.RedisConf{
				Host: m.config.Redis.Host,
				Pass: m.config.Redis.Pass,
				Type: m.config.Redis.Type,
			})
			if err != nil {
				logx.Errorf("redis init error: %v", err)
			}
			token,_ = strings.CutPrefix(token, common.AuthorizationPrefix)
			// 目前是可以多端登录
			// 校验token
			strUserinfo,err := rds.GetCtx(r.Context(),common.AuthorizationHeader + token)
			if err != nil {
				errResBytes,_ := json.Marshal(types.CommonResponse{
					Status: 500,
					Msg: "请重新登录",
				})
				w.Write(errResBytes)
				return
			}
			
			var userInfo types.User

			rds.ExpireCtx(r.Context(),common.AuthorizationHeader + token,common.ExpireTime)
			_ = json.Unmarshal([]byte(strUserinfo),&userInfo)
			ctx := context.WithValue(r.Context() ,common.ContextAuth ,userInfo)
			req := r.WithContext(ctx)
			next(w,req)
			return
		}
		errResBytes,_ := json.Marshal(types.CommonResponse{
			Status: 500,
			Msg: "请重新登录",
		})
		w.Write(errResBytes)
	}
}
